#include "login.h"
#include "ui_login.h"

Login::Login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Login)
{
    ui->setupUi(this);

    m_StartNetServer = new Netserver_udp("192.168.0.101", 9000, 9000);
    m_Timer = new QTimer(this);

    i = 0;
    m_Register = new Register(0, m_StartNetServer);

    ui->progressBar->hide();
    connect(ui->pBlogin,SIGNAL(clicked()),this,SLOT(m_LoginProcess()));
    connect(ui->pBregister,SIGNAL(clicked()),this,SLOT(m_RegisterProcess()));
}

Login::~Login()
{
    delete ui;
    delete m_StartNetServer;
    delete m_Timer;
}

void Login::m_LoginProcess()
{
    QByteArray send_data;

    ui->progressBar->show();
    ui->progressBar->setValue(0);


    if(true == m_Error.m_IllegalCharCheck("Login name", ui->lElogin_name->text(), 6))
        return;
    if(true == m_Error.m_IllegalCharCheck("Login password", ui->lElogin_password->text(), 6))
        return;
    ui->progressBar->setValue(25);

    send_data += SPECIAL_LOGIN;//+唯一码
    send_data.append(ui->lElogin_name->text());//+名字
    send_data.append(ui->lElogin_password->text());//+密码
    m_Error.m_Format(&send_data, m_StartNetServer->m_GetIp(), 15, ' ');//+ip
    ui->progressBar->setValue(50);

    m_StartNetServer->m_SendMessageProcess(send_data);
    ui->progressBar->setValue(75);

    m_Timer->start(400);//10s timer

    disconnect(ui->pBlogin,SIGNAL(clicked()),this,SLOT(m_LoginProcess()));
    connect(this->m_Timer,SIGNAL(timeout()),this,SLOT(m_TimeroutProcess()));
    connect(this->m_StartNetServer->m_UdpDescribe,SIGNAL(readyRead()),this,SLOT(m_WaitServerProcess()));
}

void Login::m_TimeroutProcess()
{
    if(i++ == 24){
        m_Error.m_ErrorPlay("Timerout","Connect Chat book Server Error!");
        m_Timer->stop();
        disconnect(this->m_StartNetServer->m_UdpDescribe,SIGNAL(readyRead()),this,SLOT(m_WaitServerProcess()));
        connect(ui->pBlogin,SIGNAL(clicked()),this,SLOT(m_LoginProcess()));
        i = 0;
    }else
        ui->progressBar->setValue(75 + i);
}

void Login::m_WaitServerProcess()
{
    QByteArray recive_data = m_StartNetServer->m_ReciveMessageProcess();
    if(SPECIAL_LOGIN != recive_data.at(1))
        return;
    m_Timer->stop();
    i = 0;
    switch(recive_data.at(2))
    {
    case SPECIAL_LOGIN_ERROR_NAME://用户不存在
        m_Error.m_ErrorPlay("Login","User name Error!");;
        break;
    case SPECIAL_LOGIN_ERROR_PASSWORD://密码错误
        m_Error.m_ErrorPlay("Login","User password Error!");
        break;
    case SPECIAL_LOGIN_SUCCESS://成功入口

        this->close();
        break;
    default:
        m_Error.m_ErrorPlay("Login","Recive user data Error!");
    }
    connect(ui->pBlogin,SIGNAL(clicked()),this,SLOT(m_LoginProcess()));
}

void Login::m_RegisterProcess()
{
    m_Register->show();
}
